package com.zmj.service;

import com.zmj.dao.UserDao;
import com.zmj.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@Service
public class UserService {
    @Autowired
    private UserDao userDao;

    /**
     * 登录业务
     */
    public User login(User user){
        User loginUser = userDao.getUserByName(user.getName());
        // 用户输入的密码使用md5加密后，才和数据库里的比较
//        String userPwd = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());
        if (loginUser != null && loginUser.getPassword().equals(user.getPassword())){
            // 账号存在，且密码相同，发放随机数作为本次登录的token
            loginUser.setToken(UUID.randomUUID().toString());
            // 把token存到数据库
            userDao.setTokenToUser(loginUser);
            return  loginUser;

        }else {
            return null;
        }
    }
    /**
     * 注册业务
     */
public User regist(User user){
    if (userMapper.getUserByAccount(user.getName())!=null){
        return null;
    }
    //注册之前先把表单传过来的密码根据MD5加密
    String newPwd = DigestUtils.md5DigestAsHex((user.getPassword() + "mlkh21256257282931").getBytes());
    //加密后在重新注入到user实体里
    user.setPassword(newPwd);
    //根据dao层的register方法判断是否操作成功
    boolean isSuccess = userMapper.register(user) > 0;

    if (isSuccess) {
        //如果成功就返回对象
        return user;
    } else {
        //失败就返回null
        return null;
    }
}

    public User getUserByToken(HttpServletRequest request) {
        String token = request.getHeader("TOKEN");
        if (token == null) {
            return null;
        }
        return userDao.getUserByToken(token);
    }

}
